/*
 * @Author: Jone XIn
 * @Date: 2022-01-24 21:02:45
 * @LastEditTime: 2022-01-26 23:48:32
 * @Description: 绘图
 */
import layout from "./layout.js";
import {
    data,
    defaultMaichineConfig,
    defaultProjectConfig,
    defaultServeConfig
} from "./data.js";
class Graph {

    graphData = []; // 数据源
    graph = null; // 全局的图对象

    constructor() {
        this.graphData = data;
    }

    // 初始化
    init(width, height, callback) {
        const that = this;
        this.graph = new G6.Graph({
            container: "container",
            width: width || 1200,
            height: height || 700,
            layout,
            defaultNode: {
                color: "#5B8FF9",
            },
            modes: {
                default: ["drag-canvas"],
            },
        });

        // init nodes and edge
        const nodes = this.graphData.nodes;
        this.graph.data({
            nodes,
            edges: this.graphData.edges.map(function (edge, i) {
                edge.id = "edge" + i;
                return Object.assign({}, edge);
            }),
        });

        this.graph.render();

        this.graph.on("node:dragstart", function (e) {
            that.graph.layout();
            that.refreshDragedNodePosition(e);
        });
        this.graph.on("node:drag", function (e) {
            that.refreshDragedNodePosition(e);
        });
        this.graph.on("node:dragend", function (e) {
            e.item.get("model").fx = null;
            e.item.get("model").fy = null;
        });
        // 双击事件
        this.graph.on("node:dblclick", function (evt) {
            that.handEditPoint(evt);
        });

        if (typeof window !== "undefined") {
            window.onresize = () => {
                if (!this.graph || this.graph.get("destroyed")) return;
                if (!container || !container.scrollWidth || !container.scrollHeight)
                    return;
                this.graph.changeSize(container.scrollWidth, container.scrollHeight);
            };
        }
        callback(true);
    }

    // refresh ponits
    refreshDragedNodePosition(e) {
        const model = e.item.get("model");
        model.fx = e.x;
        model.fy = e.y;
        if (e.item._cfg.model.label == "Server") {
            $('#add_project').css('left', e.x + 70);
            $('#add_project').css('top', e.y - 300);
        }
    }

    // 双击显示编辑信息
    handEditPoint(e) {
        // 点击服务器节点
        if (e.item._cfg.model.label == "Server") {
            $('#add_project').css('left', e.canvasX + 70);
            $('#add_project').css('top', e.canvasY - 300);
            $('#add_project').show();
            return;
        }

        // 点击项目节点
        if (e.item._cfg.model.type == 'donut') {
            $('#join_project').css('left', e.canvasX + 70);
            $('#join_project').css('top', e.canvasY - 300);
            $('#join_project').show();
            window.sessionStorage.clear();
            window.sessionStorage.setItem('c_sync_id', e.item._cfg.model.id);
            return;
        }
    }

    // 设备名称是否存在
    ifDeviceCreated(mId) {
        const edges = this.graphData.edges;
        for (let i = 0; i < edges.length; i++) {
            if (edges[i].target == mId) return true;
        }
        return false;
    }

    // 添加子项目节点
    addProject(projectName, mId, sync_id) {
        let isUpdate = this.ifDeviceCreated(mId);
        this.graphData = {
            nodes: [
                ...this.graphData.nodes,
                {
                    id: sync_id,
                    label: projectName,
                    ...defaultProjectConfig
                },
                {
                    id: isUpdate ? `${mId}${Date.now()}` : mId,
                    label: '设备',
                    ...defaultMaichineConfig
                },
            ],
            edges: [
                ...this.graphData.edges,
                { source: 'node_server', target: sync_id },
                { source: sync_id, target: isUpdate ? `${mId}${Date.now()}` : mId },
            ]
        }
        // 更新
        this.graph.changeData(this.graphData);
        this.graph.refresh();
    }

    // 添加子设备节点
    addDevice(projectName, mId, sync_id) {
        let isUpdate = this.ifDeviceCreated(mId);
        this.graphData = {
            nodes: this.graphData.nodes,
            edges: [
                ...this.graphData.edges,
                { source: sync_id, target: isUpdate ? `${mId}${Date.now()}` : mId },
            ]
        }
        // 更新
        this.graph.changeData(this.graphData);
        this.graph.refresh();
    }

    // 刷新在线项目，设备节点列表
    refreshOnlineProjectList(list) {
        // 处理节点
        const nodesMap = new Map();
        const nodes = [];
        const edges = [];
        let index = 0;
        list.forEach(item => {
            if (!nodesMap.has(item.sync_id)) {
                nodesMap.set(item.sync_id, item);
                nodes.push(
                    { id: item.sync_id, label: item.project_name, ...defaultProjectConfig },
                    { id: `${item.m_id}${++index}`, label: '设备', ...defaultMaichineConfig, fa_sync_id: item.sync_id },
                );
            } else {
                nodes.push(
                    { id: `${item.m_id}${++index}`, label: '设备', ...defaultMaichineConfig, fa_sync_id: item.sync_id },
                );
            }
        })

        // 处理线
        nodes.forEach(node => {
            // 项目节点
            if (node.type == 'donut') {
                edges.push({ source: 'node_server', target: node.id })
            } else {
                edges.push({ source: node.fa_sync_id, target: node.id })
            }
        })
        console.log(nodes, edges);
        this.graphData = {
            nodes: [
                { id: "node_server", label: "Server", ...defaultServeConfig },
                ...nodes
            ],
            edges
        }
        // 更新
        this.graph.changeData(this.graphData);
        this.graph.refresh();
    }
}


export default Graph;